<template>
  <Dialog
    v-model="show"
    :title="$t('login.商家账号注册')"
    width="800px"
    :close-on-click-modal="false"
    :hide-footer="true"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="0"
      class="register"
    >
      <el-form-item prop="code">
        <el-input
          v-model="formData.code"
          class="form_input"
          :placeholder="$t('login.请输入6-20位数字字母组合')"
        >
          <template #prefix>
            <div class="prefix_label">{{ $t('login.商户账号') }}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="email">
        <el-input
          v-model="formData.email"
          class="form_input"
          :placeholder="$t('login.请输入邮箱地址')"
        >
          <template #prefix>
            <div class="prefix_label">{{ $t('login.邮箱') }}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="phone">
        <el-input
          v-model="formData.phone"
          class="form_input"
          :placeholder="$t('login.请输入手机号码')"
        >
          <template #prefix>
            <div class="prefix_label">{{$t('login.手机号')}}</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="emailCode">
        <el-input
          v-model="formData.emailCode"
          class="form_input"
          :placeholder="$t('login.请输入邮箱验证码')"
        >
          <template #prefix>
            <div class="prefix_label">{{ $t('login.邮箱验证码')}}</div>
          </template>
          <template #append>
            <el-button :disabled="countdown > 0" @click="handleSendCode">
              {{ countdown > 0 ? `${countdown}s` : $t('login.获取验证码') }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          class="form_input"
          :placeholder="$t('login.请设置6~20位字母、数字或符号组成的密码')"
          show-password
        >
          <template #prefix>
            <div class="prefix_label">{{$t('login.设置密码')}}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          class="form_input"
          :placeholder="$t('login.请确认密码')"
          show-password
        >
          <template #prefix>
            <div class="prefix_label">{{$t('login.确认密码')}}</div>
          </template>
        </el-input>
      </el-form-item>

      <el-button type="primary" class="submit_btn" @click="handleSubmit" :loading="loading">
        {{ $t("login.提交注册") }}
      </el-button>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref } from "vue";
import Dialog from "@/components/Dialog.vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import Api from "@/config/api/api";
import Tools from "@/utils/tools";

const { t } = useI18n();

const show = defineModel("show");
const formRef = ref();
const countdown = ref(0);
const loading = ref(false)

const formData = ref({
  code: "",
  email: "",
  phone: "",
  password: "",
  confirmPassword: "",
});

// 验证商户账号
const validateCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t('login.请输入商户账号')));
    return;
  }
  if (!/^[a-zA-Z0-9]{6,20}$/.test(value)) {
    callback(new Error(t('login.请输入6-20位数字字母组合')));
    return;
  }
  callback();
};

// 验证邮箱
const validateEmail = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t('login.请输入邮箱地址')));
    return;
  }
  if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
    callback(new Error(t('login.请输入正确的邮箱地址')));
    return;
  }
  callback();
};

// 验证手机号
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t('login.请输入手机号码')));
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error(t('login.请输入正确的手机号码')));
    return;
  }
  callback();
};

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== formData.value.password) {
    callback(new Error(t('login.两次输入的密码不一致')));
  } else {
    callback();
  }
};

const rules = ref({
  code: [{ validator: validateCode, trigger: "blur" }],
  email: [{ validator: validateEmail, trigger: "blur" }],
  phone: [{ validator: validatePhone, trigger: "blur" }],
  password: [
    { required: true, message: t('login.请输入密码'), trigger: "blur" },
    { min: 6, max: 20, message: t('login.密码长度在6-20位之间'), trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]*$/,
      message: t('login.密码只能包含字母、数字或符号'),
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: t('login.请确认密码'), trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
});

const handleSendCode = async () => {
  try {
    // 校验邮箱
    await formRef.value.validateField(["email", "code"]);

    const params = {
      email: formData.value.email,
      code: formData.value.code,
    };
    const res = await Api.registerCode(params);
    if (res.status == 200) {
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);

      ElMessage.success(t("login.验证码发送成功"));
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
    ElMessage.error(error.message || t("login.发送验证码失败"));
  }
};

const handleSubmit = async () => {
  loading.value = true
  try {
    await formRef.value.validate();
    const params = {
      code: formData.value.code,
      email: formData.value.email,
      phone: formData.value.phone,
      password: Tools.rsaEncrypt(formData.value.password),
      // registerCode: "123456", //验证码
      registerCode: formData.value.emailCode,
    };
    const res = await Api.sellerRegister(params);
    if (res.status == 200) {
      ElMessage.success(t("login.注册成功，请前往登录！"));
      show.value = false;
    }
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error("表单验证失败:", error);
  }
};
</script>

<style scoped lang="scss">
.register {
  width: 100%;
  padding: 20px;

  .form_input {
    width: 100%;
    height: 40px;

    :deep(.el-input__wrapper) {
      padding-left: 0;
    }
  }

  .prefix_label {
    // width: 80px;
    text-align: center;
    color: #666;
    &::before {
      content: "*";
      color: #ff0000;
    }
  }

  .submit_btn {
    width: 100%;
    height: 40px;
    margin-top: 20px;
  }

  :deep(.el-input__prefix-inner) {
    background-color: rgba(248, 248, 248, 1);
    margin-left: 2px;
    width: 200px;
    display: flex;
    justify-content: center;
    margin-right: 10px;
  }
}
</style>
